<template>
  <div class="manage_message_form">
    <el-form :model="formData" ref="form" :rules="rules">
      <el-form-item
        label="道具类型"
        prop="propType"
        :label-width="formLabelWidth"
        class="no_input"
      >
        <el-radio-group
          v-model="formData.propType"
          :disabled="!!$route.query.id"
          @change="typeChange"
        >
          <el-radio :label="2">抵扣券</el-radio>
          <el-radio :label="1">广告样式</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="道具名称"
        prop="propName"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model="formData.propName"
          placeholder="请填写道具名称"
          autocomplete="off"
          style="width:370px"
          maxlength="8"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="可抵扣金额"
        prop="deductionAmount"
        :label-width="formLabelWidth"
        v-if="formData.propType === 2"
      >
        <el-input
          v-model="formData.deductionAmount"
          placeholder="请输入金额"
          style="width:100px"
        >
        </el-input>
        元
      </el-form-item>

      <el-form-item
        prop="imgList"
        :label-width="formLabelWidth"
        class="no_input img_item"
      >
        <div class="label_require" slot="label">上传图片</div>
        <div class="upload_box">
          <span class="upload_title">后台展示图</span>
          <el-upload
            class="avatar-uploader"
            :headers="{ 'st-cookie': token }"
            :action="baseUrl + '/smallTarget/score/uploadEffectPic'"
            :show-file-list="false"
            drag
            :on-success="handleSuccessFirst"
          >
            <div
              v-if="formData.firstPictureUrl"
              :style="`background-image: url('${formData.firstPictureUrl}');`"
              class="avatar"
            ></div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="upload_box" v-if="formData.propType === 1">
          <span class="upload_title">APP展示图</span>
          <el-upload
            class="avatar-uploader"
            :headers="{ 'st-cookie': token }"
            :action="baseUrl + '/smallTarget/score/uploadEffectPic'"
            :show-file-list="false"
            drag
            :on-success="handleSuccessSecond"
          >
            <div
              v-if="formData.secondPictureUrl"
              :style="`background-image: url('${formData.secondPictureUrl}');`"
              class="avatar"
            ></div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="价格" prop="needScore" :label-width="formLabelWidth">
        <el-input
          v-model="formData.needScore"
          placeholder="请输入价格"
          style="width:100px"
        >
        </el-input>
        积分
      </el-form-item>
      <el-form-item
        label="有效期"
        prop="duration"
        :label-width="formLabelWidth"
      >
        <el-radio-group v-model="formData.duration" class="with_input">
          <el-radio :label="1">长期有效</el-radio>
          <el-radio :label="2">
            <el-input
              v-model="formData.durationNum"
              :disabled="formData.duration === 1"
              @blur="inputBlur('duration')"
              style="width:50px"
            >
            </el-input>
            日
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="优惠方式" prop="price" :label-width="formLabelWidth">
        <el-radio-group v-model="formData.price" class="with_input">
          <el-radio :label="1">无</el-radio>
          <el-radio :label="2">
            首条
            <el-input
              v-model="formData.deductionAmountNum"
              :disabled="formData.price === 1"
              @blur="inputBlur('price')"
              placeholder="请输入价格"
              style="width:100px"
            >
            </el-input>
            积分
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="是否显示挂件"
        prop="showRule"
        :label-width="formLabelWidth"
        class="no_input"
      >
        <el-radio-group v-model="formData.showRule">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">显示限时兑换</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 上线中状态不可修改 -->
      <el-form-item label="展示时间" :label-width="formLabelWidth">
        <el-date-picker
          v-model="formData.showDay"
          type="date"
          :disabled="detail.status === 1"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
        <el-time-picker
          class="show_time_select"
          v-model="formData.showTime"
          format="HH:mm"
          :disabled="detail.status === 1"
          :picker-options="timePickOptions"
        >
        </el-time-picker>
      </el-form-item>
    </el-form>
    <slot :getFormData="getFormData"> </slot>
  </div>
</template>

<script>
import { validTrim, validNumber } from "@/utils/validate";
import { getToken } from "@/utils/auth";
import { URL_ENV } from "@/utils/request";
import moment from "moment";
export default {
  name: "ManageMessageForm",
  props: {
    detail: {
      type: Object,
      default: {}
    }
  },
  components: {},
  data() {
    const defaultForm = {
      deductionAmount: "",
      showRule: 0,
      duration: 1,
      durationNum: "7",
      deductionAmountNum: "",
      price: 1,
      firstPictureUrl: "",
      secondPictureUrl: "",
      showDay: "",
      showTime: ""
    };
    return {
      baseUrl: URL_ENV[process.env.VUE_APP_CURRENTMODE],
      formLabelWidth: "144px",
      formData: {
        propType: 2,
        ...defaultForm
      },
      pickerOptions: {
        disabledDate(time) {
          const current = moment(time);
          const start = moment().subtract(1, "days");

          return current.isBefore(start);
        }
      },
      timePickOptions: {
        selectableRange: `${moment().format("HH:mm:ss")} - 23:59:59`
      },
      defaultForm,
      token: getToken(),
      rules: {
        propType: [
          {
            required: true,
            message: "请选择公告类型",
            trigger: "change"
          }
        ],
        propName: [
          {
            required: true,
            message: "请填写道具名称",
            trigger: "blur"
          },
          {
            validator: validTrim,
            message: "请填写道具名称",
            trigger: "blur"
          }
        ],
        deductionAmount: [
          {
            required: true,
            message: "请填写金额",
            trigger: "blur"
          },
          {
            validator: validTrim,
            message: "请填写金额",
            trigger: "blur"
          },
          {
            validator: validNumber,
            message: "请输入正整数",
            trigger: "blur"
          }
        ],
        imgList: [
          {
            validator: this.validateImg,
            trigger: "change"
          }
        ],
        needScore: [
          {
            required: true,
            message: "请填写价格",
            trigger: "blur"
          },
          {
            validator: validTrim,
            message: "请填写价格",
            trigger: "blur"
          },
          {
            validator: validNumber,
            message: "请输入正整数",
            trigger: "blur"
          }
        ],
        duration: [
          {
            required: true,
            message: "请选择有效期",
            trigger: "blur"
          },
          {
            validator: this.validateDuration,
            trigger: "change"
          }
        ],
        price: [
          {
            required: true,
            message: "请选择优惠方式",
            trigger: "blur"
          },
          {
            validator: this.validateDeductionAmount,
            trigger: "change"
          }
        ],
        showRule: [
          {
            required: true,
            message: "请选择是否显示限时兑换",
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {},
  watch: {
    detail: function() {
      this.setFormData();
    }
  },
  created() {
    if (this.$route.query.id) {
      this.setFormData();
    }
  },
  methods: {
    typeChange(val) {
      if (val === 1) {
        this.formData.duration = 2;
        this.formData.durationNum = 7;
      } else {
        this.formData.duration = 1;
      }
    },
    setFormData() {
      this.formData = {
        ...this.formData,
        ...this.detail,
        firstPictureUrl: this.detail.showEffectPic
      };
      // 广告样式下设置app展示图
      if (this.detail.propType === 1) {
        this.formData.secondPictureUrl = this.detail.effectPic;
      } else {
        this.formData.deductionAmount = this.detail.deductionAmount;
      }
      // 设置优惠方式
      if (!this.detail.discount) {
        this.formData.price = 1;
      } else {
        this.formData.price = 2;
        this.formData.deductionAmountNum = this.detail.price;
      }
      // 设置有效期
      if (this.detail.duration === -1) {
        this.formData.duration = 1;
        this.formData.durationNum = 7;
      } else {
        this.formData.duration = 2;
        this.formData.durationNum = this.detail.duration;
      }
      if (this.detail.showTime) {
        this.formData.showDay = moment(this.detail.showTime).format(
          "YYYY-MM-DD"
        );
        this.formData.showTime = this.detail.showTime;
      }
    },

    inputBlur(item) {
      this.$nextTick(() => {
        this.$refs.form.validateField(item);
      });
    },
    getFormData(cb) {
      this.$refs.form.validate((valid, object) => {
        if (valid) {
          const {
            propType, // 道具类型
            propName, // 道具名称
            deductionAmount, // 抵扣券可抵扣金额
            needScore, // 价格
            duration, // 有效期
            durationNum, // 有效期天数
            price, // 优惠方式
            deductionAmountNum, // 优惠积分
            showRule, // 是否显示挂件
            firstPictureUrl, // 第一张图
            secondPictureUrl, // 第二张图
            showDay, // 展示日期
            showTime // 展示时间
          } = this.formData;
          const _showTime =
            showDay && showTime
              ? `${moment(showDay).format("YYYY-MM-DD")} ${moment(
                  showTime
                ).format("HH:mm")}`
              : moment()
                  .subtract(1, "minute")
                  .format("YYYY-MM-DD HH:mm");
          if (
            moment(_showTime).isBefore(
              moment().subtract(1, "minute"),
              "minute"
            ) &&
            this.detail.status === 0
          ) {
            return this.$message({
              type: "error",
              message: "展示时间不得早于当前时间"
            });
          }
          const obj = {
            propType,
            propName,
            needScore,
            duration: duration === 1 ? -1 : durationNum,
            discount: price === 1 ? 0 : 1, // 是否有优惠
            showRule,
            showEffectPic: firstPictureUrl, // 后台展示图
            showTime: `${_showTime}:00`
          };
          if (obj.discount) {
            obj.price = deductionAmountNum;
          }
          if (propType === 1) {
            obj.effectPic = secondPictureUrl; // APP展示图
          } else {
            obj.deductionAmount = deductionAmount; // 抵扣券可抵扣金额
          }
          if (cb) {
            cb(obj);
          }
        }
      });
    },

    validateImg(rule, str, callback) {
      if (this.formData.propType === 2) {
        if (this.formData.firstPictureUrl) {
          callback();
        } else {
          callback(new Error("请上传后台展示图"));
        }
      } else {
        if (this.formData.firstPictureUrl && this.formData.secondPictureUrl) {
          callback();
        } else {
          callback(new Error("请上传后台展示图和APP展示图"));
        }
      }
    },

    validateDuration(rule, str, callback) {
      const reg = /^\d+$/g;
      if (this.formData.duration === 2) {
        if (!this.formData.durationNum) {
          callback(new Error("请输入有效期"));
        } else if (reg.test(this.formData.durationNum)) {
          callback();
        } else {
          callback(new Error("请输入数字形式的有效期"));
        }
      } else {
        callback();
      }
    },

    validateDeductionAmount(rule, str, callback) {
      const reg = /^\d+$/g;
      const deductionAmountNum = this.formData.deductionAmountNum.toString();
      if (this.formData.price === 2) {
        if (!deductionAmountNum) {
          callback(new Error("请输入价格"));
        } else if (reg.test(deductionAmountNum)) {
          callback();
        } else {
          callback(new Error("请输入数字形式的价格"));
        }
      } else {
        callback();
      }
    },

    handleSuccessFirst(response, file) {
      const { status, entity, msg } = response;
      if (!status) {
        this.$message({
          message: msg || "网络不给力，请稍后再试",
          type: "error"
        });
      } else {
        file.url = entity.url;
        this.formData.firstPictureUrl = entity.url;
      }
    },

    handleSuccessSecond(response, file) {
      const { status, entity, msg } = response;
      if (!status) {
        this.$message({
          message: msg || "网络不给力，请稍后再试",
          type: "error"
        });
      } else {
        file.url = entity.url;
        this.formData.secondPictureUrl = entity.url;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.manage_message_form {
  .upload_box {
    display: inline-block;
    margin-right: 12px;
    vertical-align: top;
  }
  .upload_title {
    color: #404040;
    margin-bottom: 10px;
    display: inline-block;
  }
  .avatar {
    width: 320px;
    height: 60px;
    display: block;
    background-size: contain;
    // background-position: center;
    background-repeat: no-repeat;
  }

  .with_input {
    .el-radio-group {
      line-height: 40px;
    }
  }
}
</style>
<style lang="scss">
.manage_message_form {
  .avatar-uploader-icon,
  .el-upload-dragger {
    font-size: 14px;
    color: #8c939d;
    width: 320px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
}
</style>
